//
//  MNDCreditorInvestViewController.m
//  minidai
//
//  Created by 谭谭伟 on 17/5/22.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDCreditorInvestViewController.h"
#import "MNDFinaceDetailModel.h"
#import "MNDInvestModel.h"
#import "MNDBuyCreditorModel.h"
#import "MNDDepositAlertViewController.h"
#import "MNDInvestSuccessViewController.h"
#import "MNDRechargeViewController.h"
#import "FTPopOverMenu.h"
#import "MNDWebViewController.h"
#import "MNDDiscountViewController.h"
#import "MNDDepositWebViewController.h"
#import "MNDOpenDeposAlertViewController.h"
#import "MNDOpenDepositoryViewController.h"
#import "MNDOpenDepositoryPaymentViewController.h"
#import "MNDOpenDepositoryTenderViewController.h"
#import "MNDOpenDepositoryTransferViewController.h"
#import "MNDUserModel.h"
#import "MNDRiskAssessWebViewController.h"
#import "UIImage+JKColor.h"
#import <TTTAttributedLabel.h>
#import "MNDInvestFailedViewController.h"
#import "MNDOpenTermsAuthViewController.h"

@interface MNDCreditorInvestViewController () <UITextFieldDelegate, TTTAttributedLabelDelegate>
//标题
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
//年化收益率
@property (weak, nonatomic) IBOutlet UILabel *yearAprLabel;
//投资期限
@property (weak, nonatomic) IBOutlet UILabel *deadlineLabel;
//剩余可投
@property (weak, nonatomic) IBOutlet UILabel *remainingableLabel;
//充值按钮
@property (weak, nonatomic) IBOutlet UIButton *lackMoneyBtn;
//充值提示文字
@property (weak, nonatomic) IBOutlet UILabel *lackMoneyTipLabel;
//可用余额
@property (weak, nonatomic) IBOutlet UILabel *usableMoneyLabel;
//投资金额
@property (weak, nonatomic) IBOutlet UITextField *investMoneyTextField;
//折让金额
@property (weak, nonatomic) IBOutlet UILabel *discountLabel;
//应计利息
@property (weak, nonatomic) IBOutlet UILabel *aprLabel;

//应付金额
@property (weak, nonatomic) IBOutlet UILabel *costMoneyLabel;
//预期收益
@property (weak, nonatomic) IBOutlet UILabel *proEarnMoneyLabel;
//赠利券
@property (weak, nonatomic) IBOutlet UILabel *interestTickerLabel;
/* 模型数据 */
@property (strong, nonatomic) MNDFinaceDetailModel *finaceDetailModel;

//债权投资数据
@property (strong, nonatomic) MNDBuyCreditorModel *creditorModel;
//债权投资数据
@property (strong, nonatomic) MNDInvestModel *investModel;

@property (weak, nonatomic) IBOutlet UIView *investTickerView;

@property (nonatomic, copy) NSString *userPhone;

@property (nonatomic, strong) MNDUserModel *userModel;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet TTTAttributedLabel *accordLabel;
@property (weak, nonatomic) IBOutlet UIButton *accordAgreeButton;

@property (weak, nonatomic) IBOutlet UIButton *submitButton;


@end

@implementation MNDCreditorInvestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (@available(iOS 11, *)) {
        self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
//    self.leftBarTintColor = [UIColor whiteColor];
    [self.investTickerView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickinterestTickerView)]];
    
    self.costMoneyLabel.text = @"0.00";
    
    [self addAgreementLabelAttribute];
    
    [self.submitButton setBackgroundImage:[UIImage jk_imageWithColor:[UIColor colorWithRed:91/255.0 green:141/255.0 blue:231/255.0 alpha:1.0]] forState:UIControlStateNormal];
    [self.submitButton setBackgroundImage:[UIImage jk_imageWithColor:kColorGray] forState:UIControlStateDisabled];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    //导航条透明
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
    [self setupUI];
    
    [self loadData];
    
    if ([MNDLoginUserModel isUserLogin]) {
        
        [self loadUserInfo];
        
        [self loadUserPhone];
    }
    
    [self initBackButtonItem];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    //导航条透明
    [self.navigationController.navigationBar setBackgroundImage:[UIImage jk_imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    UIImage *image = [UIImage jk_imageWithColor:[UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:0.3]];
    self.navigationController.navigationBar.shadowImage = image;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}];
    
}

- (void)initBackButtonItem {
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    
    UIImage *itemImage = [UIImage imageNamed:@"navi_back_btn_black"];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage: itemImage
                                                             style: UIBarButtonItemStylePlain
                                                            target: self
                                                            action: @selector(backAction:)];
    
    
    [item setTintColor:kColorBlack];
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = item;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, item];
    }
    for (UIBarButtonItem *item in self.navigationItem.leftBarButtonItems) {
        [item setTintColor:[UIColor whiteColor]];
    }
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]}];
//    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:]}];
}

#pragma mark - Action

- (void)backAction:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)addAgreementLabelAttribute {
    //设置高亮颜色
    self.accordLabel.highlightedTextColor = kColorBlack;
    //检测类型
    self.accordLabel.enabledTextCheckingTypes = NSTextCheckingTypeLink;
    //代理
    self.accordLabel.delegate = self;
    //不显示下划线
    self.accordLabel.linkAttributes = @{(NSString *)kCTUnderlineStyleAttributeName: [NSNumber numberWithBool:NO]};
    
    NSString *text = @"我已阅读并同意签署《债权转让协议》《网络借贷风险和禁止性行为提示书》";
    [self.accordLabel setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
        NSRange linkRange1 = [[mutableAttributedString string] rangeOfString:@"我已阅读并同意签署" options:NSCaseInsensitiveSearch];
        NSRange linkRange2 = [[mutableAttributedString string] rangeOfString:@"《债权转让协议》" options:NSCaseInsensitiveSearch];
        NSRange linkRange3 = [[mutableAttributedString string] rangeOfString:@"《网络借贷风险和禁止性行为提示书》" options:NSCaseInsensitiveSearch];
        
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: kColorLightGray} range:linkRange1];
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: kColorBlue} range:linkRange2];
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: kColorBlue} range:linkRange3];
        
        return mutableAttributedString;
    }];
    
    NSRange linkRange1 = [text rangeOfString:@"我已阅读并同意签署" options:NSCaseInsensitiveSearch];
    NSURL *url1 = [NSURL URLWithString:@"http://baidu.com"];
    NSRange linkRange2 = [text rangeOfString:@"《债权转让协议》" options:NSCaseInsensitiveSearch];
    NSURL *url2 = [NSURL URLWithString:[API_BASE_URL stringByAppendingString:kTransferAccordUrl]];
    NSRange linkRange3 = [text rangeOfString:@"《网络借贷风险和禁止性行为提示书》" options:NSCaseInsensitiveSearch];
    NSURL *url3 = [NSURL URLWithString:[API_BASE_URL stringByAppendingString:kRiskTipAccordUrl]];
    [self.accordLabel addLinkToURL:url1 withRange:linkRange1];
    [self.accordLabel addLinkToURL:url2 withRange:linkRange2];
    [self.accordLabel addLinkToURL:url3 withRange:linkRange3];
}

- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    if ([url.absoluteString containsString:@"baidu.com"]) {
        [self agreeAccordAction:self.accordAgreeButton];
        
        return;
    }
    MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
    webVC.webViewUrl = url.absoluteString;
    webVC.loadType = LoadTypeLink;
    webVC.naviBarHidden = NO;

    if ([url.absoluteString isEqualToString:[API_BASE_URL stringByAppendingString:kRiskTipAccordUrl]]) {
        webVC.title = @"网络借贷风险和禁止性行为提示书";
    } else {
        webVC.title = @"债权转让协议";
    }

    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:webVC];

    [self presentViewController:navVC animated:YES completion:^{

    }];
}

- (IBAction)agreeAccordAction:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    
    self.submitButton.enabled = sender.isSelected;
}

//点击进入赠利券列表
- (void)clickinterestTickerView {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
    MNDDiscountViewController *discountVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDDiscountViewController"];
    [self.navigationController pushViewController: discountVC animated:YES];
    //    [NetworkProgressHUD showHudMsg:@"页面制作中，请耐心等候"];
}



#pragma mark -加载数据
- (void)loadData {
    [self.view beginLoading];
    __weak typeof(self) weakSelf = self;
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"borrow_code"  : self.borrowCode,
                                                          @"creditor_code": self.creditorCode}];
    
    [APIManager sendRequestWithPath:API_FINANCE_DETAIL parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakSelf.finaceDetailModel = [MNDFinaceDetailModel mj_objectWithKeyValues:responseModel.data];
            [weakSelf configContents];
            [weakSelf loadInvestData];
        } else {
            [weakSelf.view endLoading];
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            [weakSelf backToPrevious];
        }
    } onFailure:^(NSError *error) {
        [weakSelf.view endLoading];
        [NetworkProgressHUD showHudNetworkError: error];
        [weakSelf backToPrevious];
    }];
}

//获取投资数据
- (void)loadInvestData{
    WeakSelf(self)
    //请求投资
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"creditor_code":self.creditorCode}];
    
    [APIManager sendRequestWithPath:API_CREDITOR parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        [weakself.view endLoading];
        if(responseModel.status == ResponseSuccess) {
            weakself.creditorModel = [MNDBuyCreditorModel mj_objectWithKeyValues:responseModel.data];
            [weakself configInvestContent];
        }
        if (responseModel.status == ResponseFailure) {
            
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            [weakself backToPrevious];
        }
    } onFailure:^(NSError *error) {
        [weakself.view endLoading];
        [NetworkProgressHUD showHudNetworkError:error];
        [weakself backToPrevious];
    }];
}

- (void)backToPrevious {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
    });
}

- (void)loadUserInfo {
    
    WeakSelf(self);
    [APIManager sendRequestWithPath:API_USER_BASE_INFO parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            
            weakself.userModel = [MNDUserModel mj_objectWithKeyValues:responseModel.data];
            
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

/**
 获取存管手机号
 */
- (void)loadUserPhone {
    
    WeakSelf(self);
    
    NSDictionary *param = [MNDSign signedParam];
    [APIManager sendRequestWithPath:API_DEPOSIT_GET_PHONE parameters:param method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakself.userPhone = responseModel.data;
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败，请重试"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)configContents {
    self.titleLabel.text = _finaceDetailModel.borrow_title;
    self.yearAprLabel.text = _finaceDetailModel.borrow_year_apr;
    self.remainingableLabel.text = _finaceDetailModel.remainingable_tender;
    self.deadlineLabel.text = [NSString stringWithFormat:@"%@个月",_finaceDetailModel.borrow_deadline];
    
}

- (void)configInvestContent {
    //赠利券
    if (self.creditorModel.activation_coupon_sum.integerValue >0) {
        self.interestTickerLabel.text = @"已使用赠利券";
//        [NSString stringWithFormat:@"已激活的加息券数量%@",self.investModel.activation_coupon_sum];
    } else{
        self.interestTickerLabel.text = [NSString stringWithFormat:@"%@张赠利券待激活",self.creditorModel.need_coupon_sum];
    }
    if (self.creditorModel.activation_coupon_sum.integerValue <= 0 && self.creditorModel.need_coupon_sum.integerValue <= 0) {
        //赠利券
        self.interestTickerLabel.textColor = kColorLightGray;
        self.interestTickerLabel.text = [NSString stringWithFormat:@"暂无可用赠利券"];
    }

    //充值按钮显示与隐藏
    self.usableMoneyLabel.text = self.creditorModel.user_surplus_money;
    if (self.usableMoneyLabel.text.floatValue > 0) {//如果有钱不显示充值
        self.lackMoneyBtn.hidden = YES;
        self.lackMoneyTipLabel.hidden = YES;
    } else {//没钱则显示充值
        self.lackMoneyBtn.hidden = NO;
        self.lackMoneyTipLabel.hidden = NO;
    }
    //剩余可投
    self.remainingableLabel.text = [NSString stringWithFormat:@"%@",self.creditorModel.creditor_surplus_money];
    //设置默认投资金额
    //可投资金额
//    NSString *usableInvestStr = [self.creditorModel.creditor_surplus_money stringByReplacingOccurrencesOfString:@"," withString:@""];

//    //可投余额
//    float userMoney = usableInvestStr.floatValue;
//    //账户余额
//    NSString *usable = self.creditorModel.user_surplus_money;
//
//    //投资金额输入框内的数字
//    NSString *inputStr;
//    if (userMoney > usable.floatValue) {// 可投余额 > 账户余额
//
//        self.investMoneyTextField.text = usable;
//        inputStr = usable;
//    }else {
//        self.investMoneyTextField.text = [NSString stringWithFormat:@"%.2f",userMoney];
//        inputStr = [NSString stringWithFormat:@"%.2f",userMoney];
//    }
//    CGFloat yearApr = self.finaceDetailModel.borrow_year_apr.floatValue;
//    CGFloat daedline = self.finaceDetailModel.borrow_deadline.floatValue;
//    float num = inputStr.floatValue;
//    //计算利益
//    CGFloat money = num*yearApr*daedline/12/100*0.95 ;
//    self.proEarnMoneyLabel.text = [NSString stringWithFormat:@"%.2f",money];
    
//    double buyMoney = inputStr.doubleValue;
//    if (!self.creditorModel) {
//        return;
//    }
//    //计算应支付金额
//    double costMoney = buyMoney +(self.creditorModel.creditor_accrued_interest.doubleValue * buyMoney)/self.creditorModel.creditor_principal.doubleValue - buyMoney*(1 - self.creditorModel.creditor_discount_apr.doubleValue);
//    self.costMoneyLabel.text = [NSString stringWithFormat:@"%.2f",costMoney];
}

#pragma mark -搭建界面
- (void)setupUI {
    kdeclare_weakself;
    self.investMoneyTextField.clearsOnBeginEditing = YES;
    //充值按钮切圆角
    self.lackMoneyBtn.layer.cornerRadius = self.lackMoneyBtn.bounds.size.height*0.5;
    self.lackMoneyBtn.clipsToBounds = YES;
    //监听输入金额的变化
    [[self.investMoneyTextField rac_textSignal] subscribeNext:^(id x) {
        [weakSelf configMoneyContents];
    }];
}

//计算相应的金额
- (void)configMoneyContents {
    
    //可投资金额
    NSString *usableInvestStr = [self.creditorModel.creditor_surplus_money stringByReplacingOccurrencesOfString:@"," withString:@""];
    
    CGFloat yearApr = self.finaceDetailModel.borrow_year_apr.floatValue;
    CGFloat daedline = self.finaceDetailModel.borrow_deadline.floatValue;
    float num = self.investMoneyTextField.text.floatValue;
    //计算利益
    CGFloat money = num*yearApr*daedline/12/100*0.95 ;
    self.proEarnMoneyLabel.text = [NSString stringWithFormat:@"%.2f",money];
    
    //计算折让金额
    float discountApr = self.finaceDetailModel.discount_apr.floatValue/100;
    float discountNum = roundf((1-discountApr)*self.investMoneyTextField.text.floatValue*100)/100;
    
    self.discountLabel.text = [NSString stringWithFormat:@"%.2f",discountNum];
    
    double buyMoney = self.investMoneyTextField.text.doubleValue;
    
    //计算应支付金额
    double costMoney = buyMoney +(self.creditorModel.creditor_accrued_interest.doubleValue * buyMoney)/self.creditorModel.creditor_principal.doubleValue - buyMoney*(1 - self.creditorModel.creditor_discount_apr.doubleValue);
    self.costMoneyLabel.text = [NSString stringWithFormat:@"%.2f",costMoney > 0 ? costMoney : 0.00];
    //计算应计利息
    if (buyMoney > 0) {
        float aprMoney = roundf((buyMoney/self.creditorModel.creditor_principal.floatValue*self.creditorModel.creditor_accrued_interest.floatValue)*100)/100;
        self.aprLabel.text = [NSString stringWithFormat:@"%.2f",aprMoney];
    }
    
    //可投余额
    float userMoney = usableInvestStr.floatValue;
    //可用金额
    NSString *usable = self.creditorModel.user_surplus_money;
    
    //反算可输入出借金额
    if (userMoney > usable.floatValue) {//可投金额大于余额
        if(costMoney > usable.floatValue){
            self.costMoneyLabel.text = usable;
            float inputNum =  self.costMoneyLabel.text.floatValue/(1 + (self.creditorModel.creditor_accrued_interest.doubleValue/self.creditorModel.creditor_principal.doubleValue - (1 - self.creditorModel.creditor_discount_apr.doubleValue)));
            if (inputNum > userMoney) {//如果反算出来的金额>可投余额
                self.investMoneyTextField.text = [NSString stringWithFormat:@"%.2f",userMoney];
            }else {
                self.investMoneyTextField.text = [NSString stringWithFormat:@"%.2f",inputNum];
            }
            
            //重新计算折让金额
            float discountApr = self.finaceDetailModel.discount_apr.floatValue/100;
            float discountNum = roundf((1-discountApr)*self.investMoneyTextField.text.floatValue*100)/100;
            
            self.discountLabel.text = [NSString stringWithFormat:@"%.2f",discountNum];
            //重新计算应支付金额
            double costMoney = self.investMoneyTextField.text.doubleValue +(self.creditorModel.creditor_accrued_interest.doubleValue * self.investMoneyTextField.text.doubleValue)/self.creditorModel.creditor_principal.doubleValue - self.investMoneyTextField.text.doubleValue*(1 - self.creditorModel.creditor_discount_apr.doubleValue);
            self.costMoneyLabel.text = [NSString stringWithFormat:@"%.2f",costMoney > 0 ? costMoney : 0.00];
            NSLog(@"inputNum = %f",inputNum);
        }
    }else {
        if(costMoney > userMoney){
            self.costMoneyLabel.text = usableInvestStr;
            float inputNum =  self.costMoneyLabel.text.floatValue/(1 + (self.creditorModel.creditor_accrued_interest.doubleValue/self.creditorModel.creditor_principal.doubleValue - (1 - self.creditorModel.creditor_discount_apr.doubleValue)));
            
            if (inputNum > userMoney) {//如果反算出来的金额>可投余额
                self.investMoneyTextField.text = [NSString stringWithFormat:@"%.2f",userMoney];
            }else {
                self.investMoneyTextField.text = [NSString stringWithFormat:@"%.2f",inputNum];
            }
            //重新计算折让金额
            float discountApr = self.finaceDetailModel.discount_apr.floatValue/100;
            float discountNum = roundf((1-discountApr)*self.investMoneyTextField.text.floatValue*100)/100;
            
            self.discountLabel.text = [NSString stringWithFormat:@"%.2f",discountNum];
            
            //重新计算应支付金额
            double costMoney = self.investMoneyTextField.text.doubleValue +(self.creditorModel.creditor_accrued_interest.doubleValue * self.investMoneyTextField.text.doubleValue)/self.creditorModel.creditor_principal.doubleValue - self.investMoneyTextField.text.doubleValue*(1 - self.creditorModel.creditor_discount_apr.doubleValue);
            self.costMoneyLabel.text = [NSString stringWithFormat:@"%.2f",costMoney > 0 ? costMoney : 0.00];
        }
    }
}

//确认投资
- (IBAction)goInvestAction:(UIButton *)sender {
    
    [self confirmInvestSuccess];
}

#pragma mark -判断投资是否成功
- (void)confirmInvestSuccess{
   
    //输入金额判断
    if (self.investMoneyTextField.text.length > 0 && self.investMoneyTextField.text.floatValue >= 1) {
         [NetworkProgressHUD showHud];
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
        //请求投资
        NSString *investMoney = self.investMoneyTextField.text;
        NSDictionary *params = [MNDSign signedParamWithDict:@{@"creditor_code":self.finaceDetailModel.creditor_code,@"tender_money":investMoney}];
        
        WeakSelf(self);
        [APIManager sendRequestWithPath:API_BUY_CREDITOR parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
            
            if (responseModel.status == ResponseSuccess) {
                [NetworkProgressHUD hideHud];

                MNDInvestSuccessViewController *investSucessVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDInvestSuccessViewController"];
                investSucessVC.investMoneyStr = weakself.investMoneyTextField.text;
                investSucessVC.proEarnMoneyStr = weakself.proEarnMoneyLabel.text;
                [weakself.navigationController pushViewController:investSucessVC animated:YES];
            } else {
                [NetworkProgressHUD hideHud];
                NSDictionary *msgDict = responseModel.msg;
                if ([msgDict.allKeys containsObject:@"sign"]) {
                    if ([responseModel.msg[@"sign"] isEqualToString:kOpenAccount] ||
                        [responseModel.msg[@"sign"] isEqualToString:kSetPassword] ||
                        [responseModel.msg[@"sign"] isEqualToString:kSignPayment] ||
                        [responseModel.msg[@"sign"] isEqualToString:kSignAutoTender] ||
                        [responseModel.msg[@"sign"] isEqualToString:kSignAutoTransfer] ||
                        [responseModel.msg[@"sign"] isEqualToString:kRiskEvaluation] ||
                        [responseModel.msg[@"sign"] isEqualToString:kBandcard] ||
                        [responseModel.msg[@"sign"] isEqualToString:kExpiredSignPayment] ||
                        [responseModel.msg[@"sign"] isEqualToString:kExpiredAutotender]
                        ) {
                        [weakself showDepositAlertWithModel:responseModel];
                    }else if([responseModel.msg[@"sign"] isEqualToString:@"tender_money"]) {
                        [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
                    }
                    
                } else {
                    MNDInvestFailedViewController *failedVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDInvestFailedViewController"];
                    [weakself.navigationController pushViewController:failedVC animated:YES];
                }
            }
        } onFailure:^(NSError *error) {
            MNDInvestFailedViewController *failedVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDInvestFailedViewController"];
            [weakself.navigationController pushViewController:failedVC animated:YES];
        }];
        
    }else {
        if (self.investMoneyTextField.text.floatValue < 1 && self.investMoneyTextField.text.length > 0 ) {
            [NetworkProgressHUD showHudMsg:@"出借金额不能小于1元"];
        } else {
            [NetworkProgressHUD showHudMsg:@"请输入出借金额"];
        }
    }
}

- (void)showDepositAlertWithModel:(ResponseModel *)response {
    NSString *signStr = response.msg[@"sign"];
    
    //开通存管账户
    if ([signStr isEqualToString:kOpenAccount]) {
        
        [self showOpenAccountAlertWithModel:response];
        return;
    }
    
    //风险等级未评测
    if ([signStr isEqualToString:kRiskEvaluation]) {
        
        [self showRiskAlertView];
        return;
    }
    
    __weak MNDOpenDeposAlertViewController *alertVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDeposAlertViewController description]];
    
    __weak UIView *alertView = alertVC.view;
    [KeyWindow addSubview:alertView];
    [self.tabBarController addChildViewController:alertVC];
    
    WeakSelf(self);
    
    [alertVC.confirmButton bk_addEventHandler:^(id sender) {
        [alertView removeFromSuperview];
        [alertVC removeFromParentViewController];
        
        [weakself toOpenDepositoryWithModel:response];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    alertVC.alertMessage = response.msg[@"error"];
    alertVC.alertType = response.msg[@"sign"];
}

- (void)showOpenAccountAlertWithModel:(ResponseModel *)response {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDDepositAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:[MNDDepositAlertViewController description]];
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self.tabBarController addChildViewController:alertVC];
    
    __weak typeof(self) weakSelf = self;
    
    [alertVC.depositBtn bk_addEventHandler:^(id sender) {
        [springView removeFromSuperview];
        [alertVC removeFromParentViewController];
        [weakSelf toOpenDepositoryWithModel:response];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    [alertVC.closeBtn bk_addEventHandler:^(id sender) {
        
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainerView.frame = CGRectMake(alertVC.alertContainerView.frame.origin.x, kScreenHeight, alertVC.alertContainerView.frame.size.width, alertVC.alertContainerView.frame.size.height);
            alertVC.closeBtn.frame = CGRectMake(alertVC.closeBtn.frame.origin.x, kScreenHeight, alertVC.closeBtn.frame.size.width, alertVC.closeBtn.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
        }];
    } forControlEvents:UIControlEventTouchUpInside];
}

- (void)toOpenDepositoryWithModel:(ResponseModel *)response {
    
    NSInteger index = [self.navigationController.viewControllers indexOfObject:self];
    
    NSString *signStr = response.msg[@"sign"];
    //开通存管
    if ([signStr isEqualToString:kOpenAccount]) {
        MNDOpenDepositoryViewController *realVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryViewController description]];
        realVC.fromNaviIndex = index;
        
        [self.navigationController pushViewController:realVC animated:YES];
        
        return;
    }
    //设置交易密码
    if ([signStr isEqualToString:kSetPassword]) {
        
        [self loadPaymentPassword];
        return;
    }
    //授权3合1
    if ([signStr isEqualToString:kSignPayment] || [signStr isEqualToString:kExpiredSignPayment] || [signStr isEqualToString:kSignAutoTender] || [signStr isEqualToString:kExpiredAutotender] || [signStr isEqualToString:kSignAutoTransfer]) {
        MNDOpenTermsAuthViewController *openTermsAuthVC = [UIStoryboard viewControllerWithIdentifier:@"MNDOpenTermsAuthViewController"];
        openTermsAuthVC.fromNaviIndex = index;
        [self.navigationController pushViewController:openTermsAuthVC animated:YES];
        return;
    }
//    //设置缴费授权
//    if ([signStr isEqualToString:kSignPayment] || [signStr isEqualToString:kExpiredSignPayment]) {
//        
//        MNDOpenDepositoryPaymentViewController *paymentVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryPaymentViewController description]];
//        paymentVC.fromNaviIndex = index;
//        
//        [self.navigationController pushViewController:paymentVC animated:YES];
//        
//        return;
//    }
//    //设置自动投标
//    if ([signStr isEqualToString:kSignAutoTender] || [signStr isEqualToString:kExpiredAutotender]) {
//        
//        MNDOpenDepositoryTenderViewController *tenderVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTenderViewController description]];
//        tenderVC.isResign = [signStr isEqualToString:kExpiredAutotender];
//        if (self.userPhone.length > 0) {
//            tenderVC.fromNaviIndex = index;
//            tenderVC.phoneNumber = self.userPhone;
//            
//            [self.navigationController pushViewController:tenderVC animated:YES];
//        } else {
//            [self loadUserPhone];
//        }
//        return;
//    }
//    //设置自动债转
//    if ([signStr isEqualToString:kSignAutoTransfer]) {
//        
//        MNDOpenDepositoryTransferViewController *transferVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTransferViewController description]];
//        transferVC.messageStr = response.msg[@"error"];
//        if (self.userPhone.length > 0) {
//            transferVC.fromNaviIndex = index;
//            transferVC.phoneNumber = self.userPhone;
//            
//            [self.navigationController pushViewController:transferVC animated:YES];
//        } else {
//            [self loadUserPhone];
//        }
//        return;
//    }
}

- (void)showRiskAlertView {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您还没有完成[出借用户风险等级测评]，根据金融监管政策要求，用户需要先完成评估才能出借。" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"去测评" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSInteger index = [self.navigationController.viewControllers indexOfObject:self];
        
        MNDRiskAssessWebViewController *riskVC = [[MNDRiskAssessWebViewController alloc]init];
        riskVC.webViewUrl = self.userModel.evaluationUrl;
        riskVC.indexOfViewController = index;
        riskVC.title = @"风险测评";
        [self.navigationController pushViewController:riskVC animated:YES];
    }];
    [alert addAction:cancelAction];
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

/**
 设置交易密码
 */
- (void)loadPaymentPassword {
    
    [NetworkProgressHUD showHud];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_DEPOSIT_SET_PASSWORD parameters:[MNDSign signedParamWithDict:@{@"channel": @"app"}] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            MNDDepositWebViewController *webVC = [UIStoryboard viewControllerWithIdentifier:[MNDDepositWebViewController description]];
            webVC.htmlStr = responseModel.data;
            webVC.title = @"设置交易密码";
            NSInteger index = [weakself.navigationController.viewControllers indexOfObject:weakself];
            webVC.fromNaviIndex = index;
            
            [weakself.navigationController pushViewController:webVC animated:YES];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (IBAction)navRightButtonAction:(UIButton *)sender {
    
    FTPopOverMenuConfiguration *configuration = [FTPopOverMenuConfiguration defaultConfiguration];
    configuration.textColor = kColorGray;
    configuration.tintColor = [UIColor whiteColor];
    configuration.borderColor = [UIColor whiteColor];
    
    [FTPopOverMenu showForSender:sender withMenuArray:@[@"首页",@"客服",@"帮助中心"]
                       doneBlock:^(NSInteger selectedIndex) {
                           if (selectedIndex == 0) {//首页
                               
                               self.tabBarController.selectedIndex = 0;
                               
                               [self.navigationController popToRootViewControllerAnimated:YES];
                               
                           } else if (selectedIndex == 1) {//客服
                               MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
                               MNDWebViewController *mndWebViewController = [[MNDWebViewController alloc]init];
                               NSString *str = [NSString stringWithFormat:@"%@?user_id=%@&user_name=%@", kCustomerServiceURLStr, user.user_id, user.user_name];
                               mndWebViewController.hidesBottomBarWhenPushed = YES;
                               mndWebViewController.webViewUrl = str;
                               mndWebViewController.title = @"在线客服";
                               [self.navigationController pushViewController:mndWebViewController animated:YES];
                               
                           } else {
                               MNDWebViewController *mndWebViewController = [[MNDWebViewController alloc]init];
                               mndWebViewController.hidesBottomBarWhenPushed = YES;
                               mndWebViewController.webViewUrl = [NSString stringWithFormat:@"%@%@", WebBaseURL, HelpCenterURL];
                               mndWebViewController.naviBarHidden = YES;
                               [self.navigationController pushViewController:mndWebViewController animated:YES];
                           }
                           
                       } dismissBlock:^{
                           
                       }];
}

//点击nav更多按钮
- (IBAction)clickMoreButton:(UIButton *)sender {
    
    FTPopOverMenuConfiguration *configuration = [FTPopOverMenuConfiguration defaultConfiguration];
    configuration.textColor = kColorGray;
    configuration.tintColor = [UIColor whiteColor];
    configuration.borderColor = [UIColor whiteColor];
    configuration.menuIconMargin = 18;
    [FTPopOverMenu showForSender:sender withMenuArray:@[@"首页",@"客服",@"帮助中心"] imageArray:@[@"popup_menu_home",@"popup_menu_service",@"popup_menu_help"] doneBlock:^(NSInteger selectedIndex) {
        if (selectedIndex == 0) {//首页
            
            self.tabBarController.selectedIndex = 0;
            
            [self.navigationController popToRootViewControllerAnimated:YES];
            
        }else if (selectedIndex == 1) {//客服
            MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
            MNDWebViewController *bbsVC = [[MNDWebViewController alloc]init];
            NSLog(@"%@",user.user_name);
            NSString *str = [NSString stringWithFormat:@"%@?user_id=%@&user_name=%@", kCustomerServiceURLStr, user.user_id, user.user_name];
            bbsVC.webViewUrl = [NSString urlEncodeStr:str];
            bbsVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:bbsVC animated:YES];
            
        }else {//帮助中心
            MNDWebViewController *mndWebViewController = [[MNDWebViewController alloc]init];
            mndWebViewController.hidesBottomBarWhenPushed = YES;
            mndWebViewController.webViewUrl = [NSString stringWithFormat:@"%@%@", WebBaseURL, HelpCenterURL];
            mndWebViewController.naviBarHidden = YES;
            [self.navigationController pushViewController:mndWebViewController animated:YES];
        }
    } dismissBlock:nil];
}

#pragma mark -充值
- (IBAction)rechargeAction:(UIButton *)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Recharge" bundle:nil];
    MNDRechargeViewController *rechargeVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDRechargeViewController"];
    rechargeVC.isFromTender = YES;
    [self.navigationController pushViewController:rechargeVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//设置textfield输入内容
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.investMoneyTextField) {
        
        NSScanner      *scanner    = [NSScanner scannerWithString:string];
        NSCharacterSet *numbers;
        NSRange        pointRange  = [textField.text rangeOfString:@"."];
        
        if ((pointRange.length > 0) && (pointRange.location < range.location  || pointRange.location > range.location + range.length) )
        {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
        }
        else
        {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
        }
        
        if ([textField.text isEqualToString:@""] && [string isEqualToString:@"."] )
        {
            return NO;
        }
        
        short remain = 2; //默认保留2位小数
        
        NSString *tempStr = [textField.text stringByAppendingString:string];
        NSUInteger strlen = [tempStr length];
        if(pointRange.length > 0 && pointRange.location > 0){ //判断输入框内是否含有“.”。
            if([string isEqualToString:@"."]){ //当输入框内已经含有“.”时，如果再输入“.”则被视为无效。
                return NO;
            }
            if(strlen > 0 && (strlen - pointRange.location) > remain+1){ //当输入框内已经含有“.”，当字符串长度减去小数点前面的字符串长度大于需要要保留的小数点位数，则视当次输入无效。
                return NO;
            }
        }
        NSRange zeroRange = [textField.text rangeOfString:@"0"];
        if(zeroRange.length == 1 && zeroRange.location == 0){ //判断输入框第一个字符是否为“0”
            if(![string isEqualToString:@"0"] && ![string isEqualToString:@"."] && [textField.text length] == 1){ //当输入框只有一个字符并且字符为“0”时，再输入不为“0”或者“.”的字符时，则将此输入替换输入框的这唯一字符。
                textField.text = string;
                return NO;
            }else{
                if(pointRange.length == 0 && pointRange.location > 0){ //当输入框第一个字符为“0”时，并且没有“.”字符时，如果当此输入的字符为“0”，则视当此输入无效。
                    if([string isEqualToString:@"0"]){
                        return NO;
                    }
                }
            }
        }
        
        NSString *buffer;
        if ( ![scanner scanCharactersFromSet:numbers intoString:&buffer] && ([string length] != 0) )
        {
            return NO;
        }
        
    }
    
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
